/**
 * 替换字符串模板
 * @param content 
 * @param params 
 * @param mode 
 * @returns 
 */
export function replace(content: string, params: Record<string, any>, mode: '{{}}' | '{}' = '{{}}'): string {
    let regex = /(\{\{\s*(\w*)\s*\}\})/g
    if (mode === '{}') regex = /(\{\s*(\w*)\s*\})/g

    while (regex.exec(content)) {
        content = content.replace(new RegExp(RegExp.$1, 'g'), params[RegExp.$2]);
    }
    return content
}

/**
 * 字符串超出长度显示省略号
 */
export function ellipsis(content: string, length: number = 20): string {
    if (content.length > length) {
        return content.substr(0, length) + '...'
    } else {
        return content
    }
}

/**
 * 生成随机字符串
 */
export function geneRandomStr(length: number = 6, characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): string {
    const modes: Record<string, string> = {
        '[a-z]': 'abcdefghijklmnopqrstuvwxyz',
        '[A-Z]': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        '[0-9]': '0123456789',
    }

    Object.keys(modes).forEach(item => {
        characters = characters.replace(item, modes[item])
    })

    // length为所需长度，characters为所包含的所有字符，默认为字母+数字。
    const characterArr = characters.split('') //分割字符。
    let result = '' //返回的结果。
    while (result.length < length) {
        result += characterArr[Math.floor(Math.random() * characterArr.length)]
    }
    return result
}

/**
 * 生成 uuid，36 位字符串
 */
export function uuid(): string {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
    })
}

/**
 * 是否是数值字符串
 */
export function isNumberStr(value: string): boolean {
    return Number(value).toString() !== 'NaN'
}

export default {
    replace,
    ellipsis,
    geneRandomStr,
    uuid,
    isNumberStr,
}